package com.cloudcc.boot.utils.demo;

import com.cloudcc.boot.model.UserInfo;
import com.cloudcc.boot.utils.util.CCService;
import com.cloudcc.boot.utils.util.ConstantUtil;
import com.cloudcc.boot.utils.util.OperationService;
import com.cloudcc.client.CCObject;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class McInfoController {
	UserInfo uInfo;
	public static List<CCObject> dictList = null;
//	public String interface_url = "http://localhost:8080/riconcrm/distributor.action";
	public String interface_url = "http://dcm.ricoh.com.cn:9081/ricohcrmdev/distributor.action";
	public McInfoController(UserInfo usrInfo) {
		this.uInfo = usrInfo;
		CCService cs = new CCService(this.uInfo);
		dictList = cs.cquery("vfconfig");
	}
	
	/**
	 * 
	 * @param id MC 记录id
	 * @return
	 */
	public JSONObject sychToVMSA (String id,String processFlag) {
		JSONObject rtnInfo = new JSONObject();
		CCService cs = new CCService(this.uInfo);
		List<CCObject> users = cs.cquery("ccuser");
		JSONObject parameter = new JSONObject();
		/**
		 * MC基本信息
		 */
		List<CCObject> mcInfoList = cs.cquery("mcbaseinfo","id='" + id + "'");
		if (mcInfoList.size() > 0) {
			CCObject mcInfo = mcInfoList.get(0);
			JSONObject baseInfo = new JSONObject();
			baseInfo.put("mcno",nvlEncode(mcInfo.get("name")));
			baseInfo.put("itemno",nvlEncode(mcInfo.get("edpcode")));
			baseInfo.put("itemdescription",nvlEncode(mcInfo.get("itemdescriptionccname")));
			baseInfo.put("custno",nvlEncode(mcInfo.get("customerno")));
			baseInfo.put("customername",nvlEncode(mcInfo.get("customernameccname")));
			String chargetype =(String) mcInfo.get("chargetype");
			baseInfo.put("chargetypecode",nvlEncode(getDictId(ConstantUtil.MCINFO_CHARGETTYPE_CODE, chargetype)));
			baseInfo.put("chargedescription",nvlEncode(mcInfo.get("chargetype")));
			
			String remotediagnostics = (String)mcInfo.get("remotediagnostics");
			if ("true".equals(remotediagnostics)) {
				remotediagnostics = "02";
			} else {
				remotediagnostics = "01";
			}
			baseInfo.put("remotediagnosticsflg",remotediagnostics);
			baseInfo.put("remotefee",mcInfo.get("remotefee"));
			String itemsetflag = nvlEncode(mcInfo.get("itemsetflag"));
			if("是".equals(itemsetflag)) {
				baseInfo.put("itemsetflag","01");
			}else {
				baseInfo.put("itemsetflag","02");
			}
			String unifiedcalucation = (String)mcInfo.get("unifiedcalucation");
			if ("true".equals(unifiedcalucation)) {
				unifiedcalucation = "1";
			} else {
				unifiedcalucation = "2";
			}
			CCObject salesInfo = getSalesInfo(users, nvlEncode(mcInfo.get("ownerid")));
			if (salesInfo == null) {
				salesInfo = new CCObject("ccuser");
			}
                        String dept = nvlEncode(salesInfo.get("department"));
			if(dept != null && dept.indexOf("重点客户") != -1) {
				dept = "MA";//报价部门
			} else if(dept != null && dept.indexOf("生产型打印") != -1) {
				dept = "PP";//报价部门
			}
			baseInfo.put("unifiedcalucation",nvlEncode(unifiedcalucation));
			baseInfo.put("quotationdept",nvlEncode(dept));
			baseInfo.put("salesmancode",nvlEncode(mcInfo.get("salesmancode")));
			baseInfo.put("branchcode",nvlEncode(mcInfo.get("branchname")));
			baseInfo.put("inputuserid",getUserCode(users,mcInfo.get("createbyid")));
			baseInfo.put("inputdate",timeTransfer(mcInfo.get("createdate")));
			baseInfo.put("updateuserid",getUserCode(users,mcInfo.get("lastmodifybyid")));
			baseInfo.put("updatedate",timeTransfer(mcInfo.get("lastmodifydate")));
			parameter.put("mcBaseInfo", baseInfo.toString());
			/**
			 * MC 等级价格信息
			 */
			JSONArray mcpriceArray = new JSONArray();
			List<CCObject> mcpriceList = cs.cquery("mcgrade","mcno='" + id + "'");
                        int dn = 1;
			if (mcpriceList.size() > 0) {
				for (CCObject mcgrade : mcpriceList) {
					JSONObject mcprice = new JSONObject();
					mcprice.put("mcno",mcgrade.get("mcnoccname"));
					String metertype = nvlEncode(mcgrade.get("metertype"));
					mcprice.put("metertypecode", nvlEncode(getDictId(ConstantUtil.DiscountApply_METERTYPE_CODE, metertype)));
					mcprice.put("description",nvlEncode(mcgrade.get("metertype")));
					mcprice.put("displayno",dn);
					dn++;
					mcprice.put("lineno","1");
					mcprice.put("basicalfee",nvlEncode(mcgrade.get("basicalfee")));
					mcprice.put("salesfee",nvlEncode(mcgrade.get("salesfee")));
					mcprice.put("includedpaperqty",nvlEncode(mcgrade.get("includedpaperqty")));
					mcprice.put("salespaperqty",nvlEncode(mcgrade.get("salespaperqty")));
					mcprice.put("tdvstandard",nvlEncode(mcgrade.get("tdvstandard")));
					mcprice.put("standardsalesprice",nvlEncode(mcgrade.get("standardsalesprice")));
					mcprice.put("salesprice",nvlEncode(mcgrade.get("salesprice")));
					mcprice.put("startqty",nvlEncode(mcgrade.get("startqty")));
					mcprice.put("endqty",nvlEncode(mcgrade.get("endqty")));
					mcprice.put("salesbottomlineprice",nvlEncode(mcgrade.get("salesbottomlineprice")));
					mcprice.put("directservicecost",nvlEncode(mcgrade.get("directservicecost")));
					mcprice.put("unifiedcalucationcost",nvlEncode(mcgrade.get("unifiedcalucationcost")));
					mcprice.put("inputuserid",getUserCode(users,mcgrade.get("createbyid")));
					mcprice.put("inputdate",timeTransfer(mcgrade.get("createdate")));
					mcprice.put("updateuserid",getUserCode(users,mcgrade.get("lastmodifybyid")));
					mcprice.put("updatedate",timeTransfer(mcgrade.get("lastmodifydate")));
					mcpriceArray.add(mcprice);
				}
			}
			parameter.put("mcPrice", mcpriceArray.toString());
			JSONArray mcgroupItemArray = new JSONArray();
			/**
			 * MC套类明细
			 */
			List<CCObject> mcGroupItemList = cs.cquery("mcsetitems","mcno='" + id + "'");
			if (mcGroupItemList.size() > 0) {
				for (CCObject mcsetitem : mcGroupItemList) {
					JSONObject mcgroupitem = new JSONObject();
					mcgroupitem.put("mcno",nvlEncode(mcsetitem.get("mcnoccname")));
					mcgroupitem.put("itemsetno",nvlEncode(mcsetitem.get("itemsetno")));
					mcgroupitem.put("lineno",nvlEncode(mcsetitem.get("lineno")));
					mcgroupitem.put("itemno",nvlEncode(mcsetitem.get("edpcode")));
					mcgroupitem.put("itemdescription",nvlEncode(mcsetitem.get("itemdescriptionccname")));
					mcgroupitem.put("uom",nvlEncode(mcsetitem.get("uom")));
					mcgroupitem.put("itemgroup",nvlEncode(mcsetitem.get("itemtype")));
					mcgroupitem.put("quantity",nvlEncode(mcsetitem.get("quantity")));
					mcgroupitem.put("standardsalesprice",nvlEncode(mcsetitem.get("standardsalesprice")));
					mcgroupitem.put("salesbottomlineprice",nvlEncode(mcsetitem.get("salesbottomlineprice")));
					mcgroupitem.put("cost",nvlEncode(mcsetitem.get("costprice")));
					mcgroupitem.put("inputuserid",getUserCode(users,mcsetitem.get("createbyid")));
					mcgroupitem.put("inputdate",timeTransfer(mcsetitem.get("createdate")));
					mcgroupitem.put("updateuserid",getUserCode(users,mcsetitem.get("lastmodifybyid")));
					mcgroupitem.put("updatedate",timeTransfer(mcsetitem.get("lastmodifydate")));
					mcgroupItemArray.add(mcgroupitem);
				}
			}
			parameter.put("mcGroupItems", mcgroupItemArray.toString());
			parameter.put("mcProcessFlg", processFlag);
			try {
				//调用接口服务器
				System.out.println(parameter);
				SimpleDateFormat sdff = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
				Date timestamp = new Date();
				String token = OperationService.getToken("SynchCustMcInfoToVmsa",timestamp);
				String exps = "serviceName=SynchCustMcInfoToVmsa&timestamp="+sdff.format(timestamp)+"&verifyCode="+token
						+"&data=" + parameter.toString();
				String resultStr = OperationService.operate(interface_url,exps);
				rtnInfo = JSONObject.fromObject(resultStr);
			} catch (Exception ex) {
				ex.printStackTrace();
				rtnInfo.put("SuccessFlag", "0");
				rtnInfo.put("ErrorMessage", "Server Connected Failed");
				rtnInfo.put("ReturnData", "");
			}
			System.out.println(parameter);
			rtnInfo.put("SuccessFlag", "1");
			rtnInfo.put("ErrorMessage", "");
			rtnInfo.put("ResultData", "[]");
		} else {
			rtnInfo.put("SuccessFlag", "0");
			rtnInfo.put("ErrorMessage", "MC信息查询出错，请联系管理员获取支持！");
			rtnInfo.put("ResultData", "[]");
		}
		return rtnInfo;
	}
	public static void main(String[] args) {

		 UserInfo uinfo = new UserInfo();
		 uinfo.put("userName", "ricoh@demo.com");
		 uinfo.put("password", "VIFM8sC7Y8lyKuSYS/7/vg==");
		 McInfoController mcc = new McInfoController(uinfo);
		 JSONObject rst = mcc.sychToVMSA("a302019649B2611IReZG","1");
		 System.out.println(rst);

	}
	/**
	 * 获取字典代码
	 * @param dictList 数据字典表数据
	 * @param dicttype_code 字典类型
	 * @param value 查找的值
	 * @return
	 */
	public String getDictId (String dicttype_code,String value) {
		String dictid = "";
		if ("".equals(value)) { 
			return dictid;
		}
		for (CCObject co : dictList) {
			String dicttype = (String)co.get("dicttype");
			String name = (String)co.get("name");
			if (name.equals(value) && dicttype.equals(dicttype_code)) {
				dictid = (String)co.get("dictid");
				break;
			}
		}
		return dictid;
	}

	/**
	 * 根据cloudcc的userId获取员工编码
	 * @param users cloudcc所有用户信息
	 * @param ccid 要获取员工编号的cloudcc用户ID
	 * @return
	 */
	public String getUserCode (List<CCObject> users,Object ccid) {
		String userCode = "";
		if (users.size() <= 0) {
			return userCode;
		} else {
			for (CCObject user : users) {
				String userid = (String)user.get("id");
				if (userid.equals(ccid)) {
					userCode =(String) user.get("employeenum");
					break;
				}
			}
			return userCode;
		}
	}
	
	/**
	 * 格式化cloudcc日期
	 * @param time
	 * @return
	 */
	public String timeTransfer (Object time) {
		if (time == null || "".equals(time)) {
			return "";
		} else {
			time = time +".000";
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			try {
				Date datetime = sdf1.parse((String)time);
				return sdf1.format(datetime);
			} catch (ParseException e) {
				return "";
			}
		}
	}
	public String dateTransfer (Object time) {
		if (time == null || "".equals(time)) {
			return "";
		} else {
			time = time +".000";
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			try {
				Date datetime = sdf1.parse((String)time);
				return sdf1.format(datetime);
			} catch (ParseException e) {
				return "";
			}
		}
	}
	public String nvlEncode (Object val) {
		if (val == null) {
			return "";
		} else {
			return String.valueOf(val);
		}
	}
	public CCObject getSalesInfo(List<CCObject> users,Object ccid) {
		CCObject ccuser = null;
		if (users.size() <= 0) {
			return ccuser;
		} else {
			for (CCObject user : users) {
				String userid = (String)user.get("id");
				if (userid.equals(ccid)) {
					ccuser = user;
				}
			}
			return ccuser;
		}
	}
}
